//Gotten from http://stackoverflow.com/questions/527089/is-it-possible-to-create-a-namespace-in-jquery
jQuery.namespace = function() {
    var a=arguments, o=null, i, j, d;
    for (i=0; i<a.length; i=i+1) {
        d=a[i].split(".");
        o=window;
        for (j=0; j<d.length; j=j+1) {
            o[d[j]]=o[d[j]] || {};
            o=o[d[j]];
        }
    }
    return o;
};

// definition
jQuery.namespace( 'jQuery.controller' );
jQuery.namespace( 'jQuery.widget' );
jQuery.namespace( 'jQuery.cache' );
jQuery.namespace( 'jQuery.wixet' );
jQuery.namespace( 'jQuery.wixet.user' );

$.wixet.user.id = $.cookie("userId");
$.getJSON("/core/user/whoAmI",function(data){
	$.wixet.user.firstName = data.firstName;
	$.wixet.user.lastName = data.lastName;
	$.wixet.user.id = data.id;
	$.wixet.user.language = data.language.language_code;
});

$.cache.widgetsLoaded = new Array();
$.cache.controllersLoaded = new Array();
$.wixet.garbage = new Array();
$.wixet.actualPage = null;
$.wixet.friendList = new Array();
$.wixet.alphanumericFilter = /(^[a-z0-9]+$)/i

$.wixet.privateMessage = function(id){
	var dialog = $('<div title="New private message">'+
			'<div class="editor"></div>'+
			'</div>').dialog({
				resizable: true,
				height:400,
				width: 500,
				modal: true,
				open: function(){
					$(this).find(".editor").editor({height:230, width:450,youtube:false,sound:false});
				},
				buttons: {
					'Cancel': function() {
						$(this).dialog('close');
					},
					'Send': function() {
						var thisDialog = $(this);
						dialog.find(".editor").editor({send: "/core/privateMessage/send/userId/"+id, callback: function(data){
							data = eval("("+data+")");
							if(data.error)
								jAlert("Error while creating blog entry: "+data.message,"Error");
							else{
								thisDialog.dialog('close');
								$.wixet.userNotice("Private message sent");
							}
						}});
					}
				}
			});
}


$.wixet.uploadPhotoDialog = function(){
	//Hacer que solo se abra si no existe
	var uploadPhotoWindow
	if(uploadPhotoWindow = $.window.getWindow("uploadPhotos"))
	{
		try{
			uploadPhotoWindow.restore();
		}catch(e)
		{
			uploadPhotoWindow.select();
		}
	}else{
		 uploadPhotoWindow = $.window({
             id: "uploadPhotos", 
             title: "Subir fotos",
             content: "<div class='uploadForm'>", // load window_block8 html content
             footerContent: '<input type="hidden" id="uploadState" value="0"><div id="uploadPhotosFooter">Selecciona las fotos que quieres subir</div>',
             containerClass: "portlet ui-widget ui-widget-content ui-helper-clearfix ui-corner-all",
             headerClass: "portlet-header-centro ui-widget-header ui-corner-all",
             frameClass: "portlet-content",
             footerClass: "portlet-content",
             onClose: function() { // a callback function while user click close button
                  if(uploadPhotoWindow.getContainer().find(".state").val() == 1)
                  {
                          jConfirm("Si cierras la ventana se cancelaran todas las subidas que no se hayan finalizado","Confirmar cierre", 
                          function (r)
                          {
                                  if(r)
                                	  uploadPhotoWindow.close(true);
                          });
                          return false;
                  }else return true;
                  }
          });
		 uploadPhotoWindow.getContainer().find(".uploadForm").photoUpload();
	}
}

$(document).ready(function() {

	//Language
	var lang = $.cookie("language");
	if(lang == null)
		lang = "es_ES";
		
	$._.setLocale(lang);
	$.get("/js/locals/config."+$._.getLocale()+".json",function(data){
		eval(data);
	});
	///
	$(document).themeswitcher();
	
if($("#chat").length)
	$("#chat").chat();

	//Historial
	$.history.init(historial);
	function historial(hash)
	{
		if($.wixet.garbage.length > 0)
		{
			for(var i = 0; i<$.wixet.garbage.length; i++)
				$.wixet.garbage[i]();
			$.wixet.garbage = new Array();
		}

		var action;
		var actionVars = new Object();
		var controller;
		
		if(hash.length == 0)
			window.location.href = "#start";

			controller = hash.split("#");
			var vars ="";
			if(controller.length == 0)
				controller = hash;
			else
			{
				//controlador	
				var actionInfo = controller[0].split("/");
				controller = actionInfo.shift();
				action = actionInfo.shift();
				
				var json = "";
				
				for(var i=0;i<actionInfo.length; i=i+2)
				{
					//To avoid xss
					if($.wixet.alphanumericFilter.test(actionInfo[i]) && $.wixet.alphanumericFilter.test(actionInfo[i+1]))
					{
						json += actionInfo[i]+":\""+actionInfo[i+1]+"\",";
						vars += "/"+actionInfo[i]+"/"+actionInfo[i+1];
					}
				}
				actionVars = eval("({"+json.substring(0, json.length-1)+"})");
			}
			
		$("#but-"+controller).addClass("ui-state-active");
		//fin historial
		if($.wixet.actualPage != controller){
					//Widgets
					$.wixet.actualPage = controller;
					$.getJSON("layout/get/section/"+controller+""+vars,
			        function(data){
						
						$("#columnRight").html("");
						$("#columnLeft").html("");
						$("#columnCenter").html("");
						  $.each(data, function(i,widgetData){
							  
							  var widgetName = widgetData.title;
							  var widget = widgetData.name;
							  var minimized = widgetData.min == 1;
							  var column;
							//Creamos el bloque
							  if(widgetData.column == null)
								  column = $("#columnCenter");
							  else{
								  if(widgetData.column == 1)
									column = $("#columnLeft");
								  else
									column = $("#columnRight");	
							  }
								  
							  
									column.append('<div id="widget-'+widget+'" class="widget portlet ui-widget ui-widget-content ui-helper-clearfix ui-corner-all">'+
			                                                                                                '<div class="portlet-header ui-widget-header ui-corner-all"><div class="title">'+ widgetName +'</div></div>'+
			                                                                                                '<div class="portlet-content">'+widgetData.body+
			                                                                                                '</div></div>');
			
			
			/*	                                                $(".portlet-centro").addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
				                                                .find(".portlet-header-centro")
				                                                        .addClass("ui-widget-header ui-corner-all")
				                                                        .end()
				                                                .find(".portlet-content");
			*/
			                                                if(widgetData.column != null)
			                                                {
			                                                	 $("#widget-"+widget).addClass("ui-widget ui-widget-content ui-helper-clearfix ui-corner-all")
			                                                     .find(".portlet-header")
			                                                             .addClass("move ui-widget-header ui-corner-all")
			                                                             .prepend('<span class="ui-icon ui-icon-plusthick"></span>')
			                                                             .prepend('<span class="ui-icon ui-icon-closethick"></span>')
			                                                             .end();
			                                                	 
			                                                  $("#widget-"+widget+" .portlet-header .ui-icon").click(function(event) {
			                                                        if($(event.target).attr("class").indexOf("close") > -1)
			                                                        {
			                                                                $(this).parent().parent().fadeOut();
			                                                                $.get("layout/close/widget/"+ $(this).parent().parent().attr("id").replace("widget-","") );
			                                                        }
			                                                        else
			                                                        {
			                                                                $(this).toggleClass("ui-icon-minusthick");
			                                                                $(this).parents(".portlet:first").find(".portlet-content").toggle();
			                                                                $.get("layout/roll/widget/"+ $(this).parent().parent().attr("id").replace("widget-","") );
			                                                        }
			                                                  });
			                                                }
									if(minimized) {
										$("#widget-"+widget).find(".portlet-content").toggle();
										$("#widget-"+widget).find(".portlet-header .ui-icon").toggleClass("ui-icon-minusthick");
									}
									
									//$.get("/js/widgets/"+widget+".js");
							/////////////////
							  /*$.getJSON("/"+widget+"/index/"+hash, function(data){
								$("#widget-"+widget).find(".portlet-header .title").text(data.title);
								$("#widget-"+widget).find(".portlet-content").html(data.body);
								$.get("/js/widgets/"+widget+".js");
			
							});*/
						  });
						  
			if($("#columnRight").children().length == 0)
			{
				//No hay columna derecha
				$("#columnCenter").addClass("columnCenterBig");
				$("#columnCenter").removeClass("columnCenter");
			}
			
			//Imágenes
			$(".demo img[load!=false]")
			.addClass("ui-state-default ui-corner-all")
			.lazyload({
			    placeholder : "images/progress.gif",
			    effect : "fadeIn"
			});
			
			
			
			          //Ahora se hace sortable
			          $(".column").sortable({
						connectWith: '.column',
						handle: 'div.portlet-header',
						start: function(e) {
							$(".columnCenterBig").switchClass('columnCenterBig', 'columnCenter',500);
			
						},
						stop: function(event,ui) { 
							
							if($("#columnRight").children().length == 0)
							{
								
								$(".columnCenter").switchClass('columnCenter', 'columnCenterBig',500);
								
							}
							var widgetList = new Array();
							$.each($("#columnLeft").children(),function(i,widget){
								widgetList.push({id:$(widget).attr("id").replace("widget-",""),pos:i,col:1});
							});
							$.each($("#columnRight").children(),function(i,widget){
								widgetList.push({id:$(widget).attr("id").replace("widget-",""),pos:i,col:2});
							});

						}
					  });
			
			          $(".portlet-content").unbind();
					  $("#columnCenter").show();
					  $("#columnLeft").show();
					  
						$("body").css("height",$(document).height()+"px");
						
						try{
							$.controller[controller].init(actionVars);
						}catch(e){/*console.log("aa"+controller);*//*No init method*/}
						executeController(controller,action,actionVars,true);
						
			        });
		}else executeController(controller,action,actionVars,false);
		

	}
//Fin animacion widgets


	//El dock
	$('#dock').Fisheye(
		{
			maxWidth: 50,
			items: 'a',
			itemsText: 'span',
			container: '.dock-container',
			itemWidth: 30,
			proximity: 90,
			halign : 'center'
		}
	);			
	$("#dock").find("span").addClass("portlet-header-center ui-widget-header ui-corner-all");
	//Pijada para que no se quede marcado cuando se pincha
	$(".dock-item").click(
		function()
		{
			$(this).blur();
	});
	//find dock
		
	//actividad ajax
	var cargando = $("#ajaxLoading");
	cargando.hide();
	$(document).ajaxSend(function() {
		cargando.show();

		});
	
	$(document).ajaxComplete(function() {
		cargando.hide();
		});
	//fin actividad ajax
	
	//toolbar
	//Toolbar
	$("#buttons").buttonset();

		
	$("#but-start").click(
		function () { 
		  window.location.href = "#start"; 
		  $(this).blur();
		}
    );
    $("#but-profile").click(
		function () { 
		  window.location.href = "#profile"; 
		  $(this).blur();
		}
    );
    $("#but-search").click(
		function () { 
		  window.location.href = "#search"; 
		  $(this).blur();
		}
    );
    $("#but-contents").click(
    		function () { 
    		  window.location.href = "#contents"; 
    		  $(this).blur();
    		}
        );
    
    $("#but-services").click(
    		function () { 
    		  window.location.href = "#services"; 
    		  $(this).blur();
    		}
        );
	
		//$(".column").disableSelection();
		

	//fin toolbar
		
		//Cargar lista amigos
		$.getJSON("/core/user/friendList",function(data){
			$.each(data,function(i,friend){
				$.wixet.friendList.push({value:friend.firstName+" "+friend.lastName+" "+friend.secondLastName, label:friend.firstName+" "+friend.lastName+" "+friend.secondLastName, id:friend.id});
			});
			
			$("#buscarAmigos").autocomplete({
				minLength: 2,
				source: $.wixet.friendList,
				select: function(event, ui) {
					window.location.href = "#profile/load/id/"+ui.item.id;
				
				return false;
			}

			});
		});
		
		/*
		$("body").window({
		   title: "Conversacion con alguien",
		   content: "",
		   checkBoundary: true,
		   width: 200,
		   height: 160,
		   maxWidth: 400,
		   maxHeight: 300,
		   x: 50,
		   y: 10
		});
		*/

});

/*-----------*/
function userNotice(message)
{
        $.jGrowl(message, { 
                                        theme:  'manilla',
                                        speed:  'slow'});
}

$.wixet.userNotice = function(message){
	userNotice(message);
}
/*-------------*/

function includeWidget(widget){
	var widgetName = $(widget).attr("id").substr(7);
	if($.cache.widgetsLoaded.indexOf(widgetName) < 0){
		if($.wixet.alphanumericFilter.test(widgetName)){
			$.get('/js/widget/widget-'+widgetName+'.js',function(){
				$.cache.widgetsLoaded.push(widgetName);
				//Load languages files
				$.getJSON("/js/locals/widget/"+widgetName+"/"+$._.getLocale()+".json",function(data){
					$.each(data,function(original,translation){
						jQuery.i18n.strings[original]=translation;
					});
					eval("$.widget."+widgetName+".init(widget)");
				});
					
				
	
			});
		}
	}else eval("$.widget."+widgetName+".init(widget)");
	
}





function executeController(controller,action,actionVars,loadDependecies){
	if($.wixet.alphanumericFilter.test(controller))
	{
		if(!$.wixet.alphanumericFilter.test(action) || action==null)
			action = "index";

			if(loadDependecies){
				var widgetList = $(".widget");
				var noLastCount = widgetList.length - 1;
				var i;
				for(i=0; i < noLastCount; i++){
					includeWidget(widgetList[i]);
				}
				
				if(widgetList.length>0){//Check if there are not any widget
					//Its very important that all js exists, if 404 the controller will not run
					var widgetName = $(widgetList[i]).attr("id").substr(7);
					if($.cache.widgetsLoaded.indexOf(widgetName) < 0){
						$.cache.widgetsLoaded.push(widgetName);
						if($.wixet.alphanumericFilter.test(widgetName)){
							$.get('/js/widget/'+$(widgetList[i]).attr("id")+'.js',function(){
								//Load languages files
								$.getJSON("/js/locals/widget/"+widgetName+"/"+$._.getLocale()+".json",function(data){
									$.each(data,function(original,translation){
										jQuery.i18n.strings[original]=translation;
									});
									eval("$.widget."+widgetName+".init(widgetList[i])");
									$.get('/js/controller/controller-'+controller+'.js',function(){
										
											eval("$.controller."+controller+"."+action+"(actionVars)");

									});
								});
								

							});
						}
					}else{
						//Load languages files
						$.getJSON("/js/locals/widget/"+widgetName+"/"+$._.getLocale()+".json",function(data){
							$.each(data,function(original,translation){
								jQuery.i18n.strings[original]=translation;
							});
							eval("$.widget."+widgetName+".init(widgetList[i])");
							//If the widget are loaded, the controller too (secured by loadDependecies flag)
							eval("$.controller."+controller+"."+action+"(actionVars)");
						});
						
					}
				}else {
					if($.cache.widgetsLoaded.indexOf(controller) < 0){
						$.get('/js/controller/controller-'+controller+'.js',function(){
							$.cache.controllersLoaded.push(controller);
							eval("$.controller."+controller+"."+action+"(actionVars)");
						});
					}else eval("$.controller."+controller+"."+action+"(actionVars)");
				}
			}else eval("$.controller."+controller+"."+action+"(actionVars)");

	}
}
